<?php
/**
 * JoosFish - Multi Lingual extention and translation manager for Joostina CMS
 * Copyright (C) 2011 Joostina Team
 * 
 * @name JoosFish
 * @copyright © 2011 Joostina team, © 2003-2007 Think Network GmbH, Munich
 * @license GNU General Public License version 2
 * @version 1.8.2.1
 * @package Joostina
 *
 * Based on the source code of Joom!Fish 1.8.2 copyrighted by Think
 * Network GmbH, Munich. The main contribution is made by developers of
 * Joom!Fish project, but the main reason behind making JoosFish an alongside
 * project is to maintain it's compatibility with Joostina CMS 1.3.x
 * 
 * For full copyright note see documetation/COPYRIGHT.php
 * 
 * For changes see documentation/CHANGELOG.php
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * -----------------------------------------------------------------------------
 * $Id: install.joomfish.php 8 2011-06-30 08:23:14Z hnatt88@gmail.com $
 *
*/

// Don't allow direct linking
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * General install method for the component. Useage of standard method for
 * access.
*/
function com_install()
{
	global $_VERSION, $database, $mosConfig_lang;
	require_once( mosMainFrame::getBasePath() .'/components/com_joomfish/includes/defines.php' );
	require_once( JOOMFISH_LIBPATH .DS. 'joomla' .DS. 'language.php' );
	require_once( JOOMFISH_LIBPATH .DS. 'joomla' .DS. 'registry.php' );
	$lang =& JLanguageHelper::getLanguage();
	$lang->load( 'com_joomfish', JOOMFISH_LANGPATH );

	$adminDir = dirname(__FILE__);
	if (!is_writable(mosMainFrame::getBasePath() ."/mambots/system/")){
		require( $adminDir . "/joomfish.class.php");
		require( $adminDir . "/admin.joomfish.html.php");
		HTML_joomfish_help::showMambotWarning();
		return false;
	}

 	// Insert default language
	jfInstall_languages();

	// Modify the admin icons
	$database->setQuery( "SELECT id FROM #__components WHERE name= 'Joom!Fish'" );
	$id = $database->loadResult();

	//add new admin menu images
	$database->setQuery( "UPDATE #__components SET name= 'JoosFish', admin_menu_alt = 'Content translation', admin_menu_img = '../administrator/components/com_joomfish/images/joomfish_icon.png' WHERE id='$id'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = '../administrator/components/com_joomfish/images/joomfish_icon.png' WHERE parent='$id' AND name = 'Control Panel'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/document.png', name = 'Translation' WHERE parent='$id' AND name = 'Translation'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/menus.png', name = 'Manage Translations' WHERE parent='$id' AND name = 'Manage'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/config.png', name = 'Configuration' WHERE parent='$id' AND name = 'Configuration'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/language.png', name = 'Languages' WHERE parent='$id' AND name = 'Languages'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/controlpanel.png', name = 'Content elements'  WHERE parent='$id' AND name = 'Content elements'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/help.png' WHERE parent='$id' AND name = 'Help'");
	$database->query();
	$database->setQuery( "UPDATE #__components SET admin_menu_img = 'js/ThemeOffice/credits.png' WHERE parent='$id' AND name = 'About'");
	$database->query();

    $database->setQuery("UPDATE #__components " .
            "\n SET `name` = '', `admin_menu_link` = '', `option` = '', `params` = 'jfspacer', `admin_menu_img` = '../administrator/components/com_joomfish/images/jfspacer.png' " .
            "\n WHERE `name` = 'jfspacer'");
    $database->query();

    // Install the addon files and database entries.
	jfInstall_addon_files($adminDir, $id);

	// Check if upgrade of database tables is needed (existing information will be remained
	jfUpdate_tables();

	// Update index in database
	// This statement might fail
	$database->setQuery( "ALTER TABLE `#__jf_content` DROP INDEX `jfCreateContentSQL`;" );
	$database->query();
	$database->setQuery( "ALTER TABLE `#__jf_content` ADD INDEX `jfCreateContentSQL` ( `reference_id` , `reference_field` , `reference_table` , `language_id` , `published` ) ;");
	$database->query();

	// create supporting index for the table
	$database->setQuery( "ALTER TABLE `#__jf_content` DROP INDEX `jfContent`;");
	$database->query();
	$database->setQuery( "ALTER TABLE `#__jf_content` ADD INDEX `jfContent` ( `language_id` , `reference_id` , `reference_table` , `reference_field` ) ;");
	$database->query();
	$database->setQuery( "ALTER TABLE `#__jf_content` DROP INDEX `jfReferenceTable`;");
	$database->query();
	$database->setQuery( "ALTER TABLE `#__jf_content` ADD INDEX `jfReferenceTable` ( `reference_table` ) ;");
	$database->query();

    // Information text
	require_once( $adminDir . "/joomfish.class.php");
	$joomFishManager = new JoomFishManager( dirname( __FILE__ ) );

	require_once( JOOMFISH_ADMINPATH . '/admin.joomfish.html.php' );
	if( file_exists( JOOMFISH_ADMINPATH . '/help/joomfish.help.inc_' . $mosConfig_lang . '.php' ) ){
		require_once( JOOMFISH_ADMINPATH . '/help/joomfish.help.inc_' . $mosConfig_lang . '.php' );
	} else {
		require_once( JOOMFISH_ADMINPATH .'/help/joomfish.help.inc.php' );
	}

	HTML_joomfish_help::showPostInstall();

	return;
}

/**
 * check & install languages
 */
 function jfInstall_languages() {
 	global $database;

	$database->setQuery( "SELECT count(*) FROM `#__languages`;");
	$count = $database->loadResult();
	if( $count == 0 ) {
		// Read the languages dir to find new installed languages
		$languageBaseDir = mosPathName(mosPathName(mosMainFrame::getBasePath()) . "language");
		$xmlFilesInDir = mosReadDirectory($languageBaseDir,".xml");

		$dirName = $languageBaseDir;
		$activeFiles = null;

		// XML library
		require_once( mosMainFrame::getBasePath() . "/includes/domit/xml_domit_lite_include.php" );

		//mosDebugVar($xmlFilesInDir);
		$i = 0;
		foreach($xmlFilesInDir as $xmlfile) {
			// Read the file to see if it's a valid template XML file
			$xmlDoc = new DOMIT_Lite_Document();
			$xmlDoc->resolveErrors( true );
			if (!$xmlDoc->loadXML( $dirName . $xmlfile, false, true )) {
				continue;
			}

			$element = &$xmlDoc->documentElement;

			if ($element->getTagName() != 'mosinstall') {
				continue;
			}
			if ($element->getAttribute( "type" ) != "language") {
				continue;
			}

			$langCode = substr($xmlfile,0,-4);
			$element = &$xmlDoc->getElementsByPath('name', 1);
			$langName = $element->getText();
			$database->setQuery( "INSERT INTO `#__languages` (`name`, `active`, `iso`, `code`, `shortcode`, `image`, `ordering`) VALUES ('$langName', 1, '" .strtolower(substr($langName,0, 2)). "', '$langCode', '$langCode', '', $i);");
			$database->query();
			$i ++;
		}
	}
 }

 /**
  * This method installs all addon files like bots and modules
  * This method needs to be run every full install
  *
  * @params string	adminDir	directory for the admin path
  * @params	string	id			of the component menu
  */
function jfInstall_addon_files($adminDir,$id) {
	global $database;

	// Add frontend module
	$database->setQuery( "INSERT INTO `#__modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ('JoomFish language selection', '', 2, 'user3', 0, '0000-00-00 00:00:00', 1, 'mod_jflanguageselection', 0, 0, 0, '', 0, 0);");
	$database->query();
	$moduleID = $database->insertid();
	$database->setQuery( "INSERT INTO `#__modules_menu` (`moduleid`, `menuid`) VALUES ($moduleID, 0);");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.css");
    @unlink( mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.php");
    @unlink( mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.xml");

    @rename( $adminDir. "/modules/mod_jflanguageselection.css", mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.css");
    @rename( $adminDir. "/modules/mod_jflanguageselection.php", mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.php");
    @rename( $adminDir. "/modules/mod_jflanguageselection.xml", mosMainFrame::getBasePath()."/modules/mod_jflanguageselection.xml");


	// Add content mambots
	$database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Joomfish Alternative Language contentbot', 'jfalternative', 'content', 0, 0, 1, 0, 0, 0, '0000-00-00 00:00:00', 'falt_showAS=flags');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/content/jfalternative.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/content/jfalternative.xml");

    @rename( $adminDir. "/mambots/content/jfalternative.php", mosMainFrame::getBasePath()."/mambots/content/jfalternative.php");
    @rename( $adminDir. "/mambots/content/jfalternative.xml", mosMainFrame::getBasePath()."/mambots/content/jfalternative.xml");

    // Add search bots
	$database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual category searchbot', 'jfcategories.searchbot', 'search', 0, 100, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcategories.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcategories.searchbot.xml");

	@rename( $adminDir. "/mambots/search/jfcategories.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfcategories.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfcategories.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfcategories.searchbot.xml");

    $database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual contact searchbot', 'jfcontact.searchbot', 'search', 0, 101, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcontact.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcontact.searchbot.xml");

    @rename( $adminDir. "/mambots/search/jfcontact.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfcontact.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfcontact.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfcontact.searchbot.xml");

    $database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual content searchbot', 'jfcontent.searchbot', 'search', 0, 102, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcontent.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfcontent.searchbot.xml");

    @rename( $adminDir. "/mambots/search/jfcontent.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfcontent.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfcontent.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfcontent.searchbot.xml");

    $database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual news feeds searchbot', 'jfnewsfeeds.searchbot', 'search', 0, 103, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfnewsfeeds.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfnewsfeeds.searchbot.xml");

    @rename( $adminDir. "/mambots/search/jfnewsfeeds.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfnewsfeeds.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfnewsfeeds.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfnewsfeeds.searchbot.xml");

    $database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual sections searchbot', 'jfsections.searchbot', 'search', 0, 104, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfsections.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfsections.searchbot.xml");

    @rename( $adminDir. "/mambots/search/jfsections.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfsections.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfsections.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfsections.searchbot.xml");

    $database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual weblinks searchbot', 'jfweblinks.searchbot', 'search', 0, 105, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfweblinks.searchbot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/search/jfweblinks.searchbot.xml");

    @rename( $adminDir. "/mambots/search/jfweblinks.searchbot.php", mosMainFrame::getBasePath()."/mambots/search/jfweblinks.searchbot.php");
    @rename( $adminDir. "/mambots/search/jfweblinks.searchbot.xml", mosMainFrame::getBasePath()."/mambots/search/jfweblinks.searchbot.xml");

    // Add system Bot
	$database->setQuery( "INSERT INTO `#__mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('Multi lingual abstraction layer bot', 'jfdatabase.systembot', 'system', 0, 1, 1, 0, 0, 0, '0000-00-00 00:00:00', '');");
	$database->query();
	// make sure those files do not exist anymore.
    @unlink( mosMainFrame::getBasePath()."/mambots/system/jfdatabase.systembot.php");
    @unlink( mosMainFrame::getBasePath()."/mambots/system/jfdatabase.systembot.xml");

    @rename( $adminDir. "/mambots/system/jfdatabase.systembot.php", mosMainFrame::getBasePath()."/mambots/system/jfdatabase.systembot.php");
    @rename( $adminDir. "/mambots/system/jfdatabase.systembot.xml", mosMainFrame::getBasePath()."/mambots/system/jfdatabase.systembot.xml");

    // Install mod_translate admin module - but only if target locaion is writeable
    if (is_writable(mosMainFrame::getBasePath(1)."/modules/")){
		// make sure those files do not exist anymore.
	    @unlink( mosMainFrame::getBasePath()."/administrator/modules/mod_translate_no.png");
	    @unlink( mosMainFrame::getBasePath()."/administrator/modules/mod_translate.php");
	    @unlink( mosMainFrame::getBasePath()."/administrator/modules/mod_translate.xml");
	    @unlink( mosMainFrame::getBasePath()."/administrator/modules/mod_translate.png");

	    @rename( $adminDir. "/modules/mod_translate_no.png", mosMainFrame::getBasePath()."/administrator/modules/mod_translate_no.png");
    	@rename( $adminDir. "/modules/mod_translate.php", mosMainFrame::getBasePath()."/administrator/modules/mod_translate.php");
    	@rename( $adminDir. "/modules/mod_translate.xml", mosMainFrame::getBasePath()."/administrator/modules/mod_translate.xml");
    	@rename( $adminDir. "/modules/mod_translate.png", mosMainFrame::getBasePath()."/administrator/modules/mod_translate.png");

    	// Add module
    	$database->setQuery( "INSERT INTO `#__modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ('JoomFish Direct Translation', '', 1, 'header', 0, '0000-00-00 00:00:00', 1, 'mod_translate', 0, 99, 0, 'com_content|content|cid|task|!edit
com_frontpage|content|cid|task|!edit
com_sections|sections|cid|task|!editA
com_categories|categories|cid|task|!editA
com_contact|contact_details|cid
com_menus|menu|cid|task|!edit
com_modules|modules|cid|task|!editA|client|!admin
com_newsfeeds|newsfeeds|cid|task|!editA
com_poll|poll_data|cid|task|!editA', 0, 1);");

    	$database->query();
    	$moduleID = $database->insertid();
    	$database->setQuery( "INSERT INTO `#__modules_menu` (`moduleid`, `menuid`) VALUES ($moduleID, 0);");
    	$database->query();
    }

    // remove directories that are no longer needed
    @rmdir( $adminDir. "/mambots/search");
    @rmdir( $adminDir. "/mambots/system");
    @rmdir( $adminDir. "/mambots/content");
    @rmdir( $adminDir. "/mambots");
    @rmdir( $adminDir. "/modules");
}

/**
 * This method allows a check of the database and in case needed an upgrade of fileds in the different tables
 *
 */
function jfUpdate_tables() {
	global $database;

	$jfVersion = '1.7';
	$sql = 'DESCRIBE #__jf_content original_text;';
	$database->setQuery($sql);
	if( $row = $database->loadResult() ) {
		if (count($row)>0) {
			// Field does exist => installed version is considered 1.8+
			$jfVersion = '1.8';
		}
	}

	if($jfVersion=='1.7') {
		$database->setQuery('ALTER TABLE `#__jf_content` ADD `original_text` TEXT NULL AFTER `original_value` ;');
		$database->query();

		$database->setQuery('ALTER TABLE `#__languages` CHANGE `iso` `iso` VARCHAR( 20 ) NULL DEFAULT NULL;');
		$database->query();
		$database->setQuery('ALTER TABLE `#__languages` ADD `shortcode` VARCHAR( 20 ) NULL AFTER `code`;');
		$database->query();
		$database->setQuery("ALTER TABLE `#__languages` ADD `fallback_code` varchar(20) NOT NULL default '' AFTER `image`;");
		$database->query();
		$database->setQuery('ALTER TABLE `#__languages` ADD `params` TEXT NULL AFTER `fallback_code`;');
		$database->query();
	}
}
?>